const express = require('express')

const multer = require('multer')

const path = require('path')

const mysql = require('mysql')

var cookieSession = require('cookie-session')


//连接数据库
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'mymanager',
})
//创建一个文件夹用来存放用户提交的数据
var upload = multer({
    dest: path.join(__dirname, 'www', 'uploads/')
})


let app = express()

//暴露这个文件夹
app.use(express.static('www'))

//传过来的是文本，需要处理一下才能使用req.body
app.use(express.urlencoded({
    extended: false
}))

//设置
app.use(cookieSession({
    name: 'session',
    keys: ['secure', 'key2'], //加密添加剂
    maxAge: 24 * 60 * 60 * 1000 * 7 //最大有效时长
}))

//判断是否已经登录的接口
app.get('/isLogin', (req, res) => {
    res.send({
        data: req.session.user
    })
})

//获取英雄是请求
app.get('/hero/all', (req, res) => {
    // console.log(req.query);
    if (req.query.search == undefined) {
        connection.query(`select * from hero where isdelete='false'`, function (err, results) {
            if (!err) {
                res.send({
                    code: 200,
                    data: results
                })
            } else {
                res.send({
                    code: 500,
                    msg: '服务器内部错误'
                })
            }
        })
    } else {

        //定义一个变量来存放用户搜索提交过来的变量
        let search = req.query.search
        connection.query(`select * from hero where name like '%${search}%' and isdelete='false'`, function (err, results) {
            if (!err) {
                res.send({
                    code: 200,
                    data: results
                })
            } else {
                res.send({
                    code: 500,
                    msg: '服务器内部错误'
                })
            }
        })
    }


})


//删除英雄数据---这里用的是软删除，就修改数据库中isDelete 的值为true
app.get('/hero/del', (req, res) => {

    // console.log(req.query.id);

    connection.query(`update hero set isdelete='true' where id=${req.query.id}`, function (error) {
        if (!error) {
            res.send({
                code: 204,
                msg: '删除成功'
            })
        } else {
            res.send(error)
        }
    })
})


//创建一个请求对象，并用upload.single方法来获得图片的路径
app.post('/hero/add', upload.single('icon'), (req, res) => {
    //取出用户提交的数据
    let {
        name,
        skill
    } = req.body

    //对获取到的图片路径做一个拼接
    let icon = 'http://127.0.0.1:3000/uploads/' + req.file.filename
    console.log(icon);

    //操作数据库
    connection.query(`insert into hero(name,skill,icon) value('${name}','${skill}','${icon}')`, function (err) {
        if (!err) {
            res.send({
                code: 201,
                msg: '新增成功'
            })
        } else {
            res.send({
                code: 500,
                msg: '新增失败'
            })
        }
    })
})


//创建一个通过id获得英雄数据的请求服务
app.get('/hero/getByid', (req, res) => {

    let {
        id
    } = req.query
    connection.query(`select * from hero where id=${id}`, function (error, results) {
        if (!error) {
            res.send({
                code: 200,
                data: results[0]
            })
        } else {
            res.send({
                error
            })
        }
    })

})

//创建一个编辑英雄的服务
app.post('/hero/edit', upload.single('icon'), (req, res) => {

    let {
        name,
        id,
        skill
    } = req.body


    // 判断有没有修改图片。如果没有
    if (req.file == undefined) {
        // console.log(req.body);
        // console.log(req.file);
        connection.query(`update hero set id=${id},name='${name}',skill='${skill}' where id=${id}`, (error, results) => {
            if (!error) {
                res.send({
                    code: 203,
                    msg: '修改成功'
                })
            } else {
                res.send({
                    error
                })
            }
        })
    }
    //如果有上传头像
    else {
        let icon = 'http://127.0.0.1:3000/uploads/' + req.file.filename
        connection.query(`update hero set name='${name}',skill='${skill}',icon='${icon}' where id=${id}`, (error, results) => {
            if (!error) {
                res.send({
                    code: 203,
                    msg: '修改成功'
                })
            } else {
                res.send({
                    erroe
                })
            }
        })

    }


})


//生成验证码
var svgCaptcha = require('svg-captcha');

//定义一个变量用于存放验证码
var captcha_data
app.get('/captcha', function (req, res) {
    var captcha = svgCaptcha.create();
    // req.session.captcha = captcha.text;//captcha.text才是验证码的文本
    res.type('svg');
    res.status(200).send(captcha.data); //返回验证码数据

    //把生成的验证码存起来
    captcha_data = captcha.text
});

//注册接口------------------
app.post('/register', (req, res) => {

    //接收传过来的数据
    let {
        username,
        password,
        code
    } = req.body

    //判断验证码是否正确(转成统一的小写)
    if (code.toLocaleLowerCase() == captcha_data.toLocaleLowerCase()) {
        //如果验证码正确
        connection.query(`select * from user where name='${username}'`, (error, results) => {
            if (!error) {
                if (results.length > 0) {
                    res.send({
                        code: 300,
                        msg: '该用户已存在'
                    })
                } else {
                    connection.query(`insert into user(name,password) value('${username}','${password}')`, (error, results) => {
                        if (!error) {
                            res.send({
                                code: 204,
                                msg: '注册成功'
                            })
                        }
                    })
                }
            } else {
                res.send({
                    error
                })
            }
        })


    } else {
        res.send({
            code: 500,
            msg: '验证码错误',
        })
    }

})


//登录接口
app.post('/user/login', (req, res) => {

    //拿到数据去
    let {
        username,
        password
    } = req.body

    //对照数据库
    connection.query(`select * from user where name='${username}' and password='${password}'`, (error, results) => {
        if (!error) {
            if (results.length > 0) {
                //登陆成功设置session值
                req.session.user = '登录成功设置的session值'
                res.send({
                    code: 200,
                    msg: '登录成功'
                })
            } else {
                res.send({
                    code: 400,
                    msg: '用户或密码错误'
                })
            }
        }
    })


})

//退出登录接口
app.get('/outLogin', (req, res) => {
    req.session = null
    //重定向跳转到登录首页去
    res.writeHead(302, {
        'Location': './login.html'
    })
    res.end()
})
app.listen(3000, function () {
    console.log('3000端口');
})